package com.agriculture.controller;

import com.agriculture.common.R;
import com.agriculture.entity.TblArea;
import com.agriculture.entity.User;
import com.agriculture.mapper.AddressBookMapper;
import com.agriculture.mapper.AddressBookMapperOne;
import com.agriculture.service.AddressBookService;
import com.agriculture.service.TblAreaService;
import com.agriculture.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.agriculture.entity.AddressBook;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.List;

/**
 * 地址管理
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private AddressBookMapperOne addressBookMapperOne;

    @Autowired
    private TblAreaService tblAreaService;

    /**
     * 新增地址
     * @param addressBook
     * @return
     */
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook) {
        log.info("addressBook:{}", addressBook);
        addressBookService.save(addressBook);
        return R.success(addressBook);
    }

    /**
     * 修改地址
     * @param addressBook
     * @return
     */
    @PutMapping
    public R<String> setAddress(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        log.info("地址修改成功");
        return R.success("修改地址成功");
    }

    /**
     * 删除地址
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delAddress(@RequestParam Long ids){
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getId,ids);
        addressBookService.remove(queryWrapper);
        log.info("地址删除成功");
        return R.success("地址删除成功");
    }

    /**
     * 设置默认地址
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook) {
        log.info("addressBook:{}", addressBook);
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(AddressBook::getIsDefault, 0);
        //SQL:update address_book set is_default = 0 where user_id = ?
        addressBookService.update(wrapper);

        addressBook.setIsDefault(1);
        //SQL:update address_book set is_default = 1 where id = ?
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }

    /**
     * 根据 id 查询地址
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R get(@PathVariable Long id) {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getIsDeleted, 0);
        queryWrapper.eq(AddressBook::getId, id);
        AddressBook addressBook = addressBookMapperOne.selectOne(queryWrapper);
        initAddr(addressBook);
        if (addressBook != null) {
            return R.success(addressBook);
        } else {
            return R.error("没有找到该对象");
        }
    }

    /**
     * 查询默认地址
     * @return
     */
    @GetMapping("/default/{token}")
    public R<AddressBook> getDefault(@PathVariable String token) {
        User user = JwtUtils.parseToken(token);
        AddressBook addressBook = addressBookMapperOne.getDefAddById(user.getId());
        initAddr(addressBook);
        if (null == addressBook) {
            return R.error("没有找到该对象");
        } else {
            return R.success(addressBook);
        }
    }

    /**
     * 查询指定用户的全部地址
     * @return
     */
    @GetMapping("/list/{token}")
    public R list( @PathVariable String token) {
        User user = JwtUtils.parseToken(token);
        List<AddressBook> addressBook = addressBookMapperOne.getList(user.getId());
        for (AddressBook book : addressBook) {
            initAddr(book);
        }
        if(!addressBook.isEmpty()){
            return R.success(addressBook);
        }else{
            return R.error("地址为空！");
        }
    }

    /**
     * 返回所有 area 表的信息
     * @return
     */
    @GetMapping("/getAllArea")
    public R getAllArea(){
        return R.success(tblAreaService.list());
    }

    @GetMapping("/gettest")
    public R getByUserId(HttpServletRequest request){
        Long userId = (Long) request.getSession().getAttribute("user");
        List<AddressBook> addressBook = addressBookMapperOne.getList(userId);
        for (AddressBook book : addressBook) {
            initAddr(book);
        }
        if(!addressBook.isEmpty()){
            return R.success(addressBook);
        }else{
            return R.success(addressBook);
        }
    }

    /**
     * 初始化地址
     * @param addressBook
     */
    public void initAddr(AddressBook addressBook){
        List<TblArea> tblArea = addressBook.getTblArea();
        for (TblArea area : tblArea) {
            if(area.getLevel() == 1){
                // 省
                area.setProvinceName(area.getName());
            }else if(area.getLevel() == 2){
                // 市
                area.setCityName(area.getName());
                String province = addressBookMapper.selectByCode(area.getParentId()).get(0).getName();
                area.setProvinceName(province);
            }else if(area.getLevel() == 3){
                // 区
                area.setDistrict(area.getName());
                List<TblArea> tblAreas = addressBookMapper.selectByCode(area.getParentId());
                String city = tblAreas.get(0).getName();
                area.setCityName(city);
                String province = addressBookMapper.selectByCode(tblAreas.get(0).getParentId()).get(0).getName();
                area.setProvinceName(province);
                System.out.println(tblAreas);
            }else if(area.getLevel() == 4){
                // 乡镇
                area.setDistrict(area.getName());
                // 获取 区
                TblArea tblDistrict = addressBookMapper.selectByCode(area.getParentId()).get(0);
                area.setDistrict(tblDistrict.getName());
                // 获取 市
                TblArea tblCity = addressBookMapper.selectByCode(tblDistrict.getParentId()).get(0);
                area.setCityName(tblCity.getName());
                // 获取 省
                TblArea tblProvince = addressBookMapper.selectByCode(tblCity.getParentId()).get(0);
                area.setProvinceName(tblProvince.getName());
            }
        }
    }

}





















